import React from 'react';
import { formatMessage } from 'umi-plugin-react/locale';
import { Form, Input, Tabs, Tree, Modal, Radio, Checkbox, Button, message, Row, Col, Icon } from 'antd';
import { connect } from 'dva';
import styles from './index.less';
import { getUserRoleList, postUserAuth, getUserAuthList } from '@/services/user';
const { TreeNode } = Tree;
const { TabPane } = Tabs;

class AuthorizationAddModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      queryData: {
        search: '',
        type: props.pageSource == 'application' ? 1 : props.pageSource == 'document' ? 2 : 0 /** 0 角色授权  1应用授权 2文档授权 */,
        categoryId: '',
        userType: null /** 0自建 1 应用 2通讯录 */,
        targetId: '',
      },
      userList:
        props.pageSource == 'application'
          ? [
              // { name: formatMessage({ id: 'account.authManage.authorizationAddModal.addressBook' }), id: 'BM003', userType: 2, isCheck: false, isCategory: true },
            ]
          : [
              {
                name: formatMessage({ id: 'account.authManage.authorizationAddModal.selfBuiltUser' }),
                id: 'BM001',
                userType: 0,
                isCheck: false,
                isCategory: true,
              },
              // { name: formatMessage({ id: 'account.authManage.authorizationAddModal.systemUser' }), id: 'BM002', userType: 1, isCheck: false, isCategory: true },
              // { name: '通讯录', id: 'BM003', userType: 2, isCheck: false, isCategory: true },
            ],
      disabledSelectUserIds: [],
      selectUserIds: [],
      selectUserList: [
        // { name: '部门一', id: 'BM001' },
        // { name: '部门二', id: 'BM002' },
        // { name: '人员三', id: 'RY003' },
        // { name: '人员四', id: 'RY004' },
      ],
      activeUserList: [
        { name: formatMessage({ id: 'account.authManage.authorizationAddModal.contact' }), id: 'AB001' },
        // { name: formatMessage({ id: 'account.authManage.authorizationAddModal.organization' }), id: 'BM002' },
        // { name: formatMessage({ id: 'account.authManage.authorizationAddModal.rndDepartment' }), id: 'RY003' },
      ],
    };
  }

  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }

  initData = () => {
    let { authId, pageSource, targetId } = this.props;
    let { queryData } = this.state;
    queryData.targetId = targetId;
    queryData.type = pageSource == 'application' ? 1 : pageSource == 'document' ? 2 : 0;
    this.setState(
      {
        visible: true,
        queryData,
        userList:
          pageSource == 'application'
            ? [
                // { name: '通讯录', id: 'BM003', userType: 2, isCheck: false, isCategory: true },
              ]
            : [
                {
                  name: formatMessage({ id: 'account.authManage.authorizationAddModal.selfBuiltUser' }),
                  id: 'BM001',
                  userType: 0,
                  isCheck: false,
                  isCategory: true,
                },
                // { name: '通讯录', id: 'BM003', userType: 2, isCheck: false, isCategory: true },
              ],
      },
      () => this.getAuthList()
    );
  };

  getAuthList = async () => {
    let { queryAuthData } = this.props;
    let queryData = { ...queryAuthData };
    queryData.search = '';
    queryData.current = 1;
    queryData.size = 999999;
    let res = await getUserAuthList(queryData);
    console.log(res);
    let list = res.records.map((item) => {
      return { id: item.relId, name: item.name, userType: item.userType, isCheck: true, isCategory: item.type == 1 ? false : true };
    });
    this.setState({ selectUserIds: list.map((item) => item.id), disabledSelectUserIds: list.map((item) => item.id) });
  };

  setTitleClick = (row) => {
    console.log('==============', row);
    let { queryData, userList, activeUserList } = this.state;
    const { pageSource } = this.props;
    switch (row.id) {
      case 'AB001':
        activeUserList = [{ name: formatMessage({ id: 'account.authManage.authorizationAddModal.contact' }), id: 'AB001' }];

        queryData.userType = 0;
        queryData.categoryId = 'ROOT';
        userList =
          pageSource == 'application'
            ? [
                // { name: '通讯录', id: 'BM003', userType: 2, isCheck: false, isCategory: true },
              ]
            : [
                {
                  name: formatMessage({ id: 'account.authManage.authorizationAddModal.selfBuiltUser' }),
                  id: 'BM001',
                  userType: 0,
                  isCheck: false,
                  isCategory: true,
                },
                // { name: '系统用户', id: 'BM002', userType: 1, isCheck: false, isCategory: true },
                // { name: '通讯录', id: 'BM003', userType: 2, isCheck: false, isCategory: true },
              ];
        this.setState({ queryData, userList, activeUserList });
        break;

      case 'BM001':
        activeUserList = [
          { name: formatMessage({ id: 'account.authManage.authorizationAddModal.contact' }), id: 'AB001' },
          {
            name: formatMessage({ id: 'account.authManage.authorizationAddModal.selfBuiltUser' }),
            id: 'BM001',
            userType: 0,
            isCheck: false,
            isCategory: true,
          },
        ];

        queryData.userType = 0;
        queryData.categoryId = 'ROOT';
        this.setState({ queryData, activeUserList }, () => this.getList());
        break;

      case 'BM002':
        activeUserList = [
          { name: formatMessage({ id: 'account.authManage.authorizationAddModal.contact' }), id: 'AB001' },
          { name: formatMessage({ id: 'account.authManage.authorizationAddModal.systemUser' }), id: 'BM002', userType: 1, isCheck: false, isCategory: true },
        ];
        queryData.userType = 1;
        queryData.categoryId = 'ROOT';
        this.setState({ queryData, activeUserList }, () => this.getList());
        break;

      case 'BM003':
        activeUserList = [
          { name: formatMessage({ id: 'account.authManage.authorizationAddModal.contact' }), id: 'AB001' },
          // { name: '通讯录', id: 'BM003', userType: 2, isCheck: false, isCategory: true }
        ];
        queryData.userType = 2;
        queryData.categoryId = 'ROOT';
        this.setState({ queryData, activeUserList }, () => this.getList());
        break;

      default:
        let ids = activeUserList.map((item) => item.id);
        let list = activeUserList.slice(0, ids.indexOf(row.id) + 1);
        queryData.categoryId = row.id;
        this.setState({ queryData, activeUserList: [...list] }, () => this.getList());
        break;
    }
  };

  setClick = (row) => {
    let { queryData, activeUserList } = this.state;
    activeUserList.push(row);
    queryData.userType = row.userType;
    if (row.id == 'AB001' || row.id == 'BM001' || row.id == 'BM002' || row.id == 'BM003') {
      queryData.categoryId = 'ROOT';
    } else {
      queryData.categoryId = row.id;
    }
    this.setState({ queryData, activeUserList }, () => this.getList());
  };

  getList = async () => {
    const { queryData } = this.state;
    let res = await getUserRoleList(queryData);
    console.log(res);
    if (res.code === 0) {
      let categoryList = res.data.categoryList.map((item) => ({ ...item, isCheck: true, isCategory: true }));
      let userDataList = res.data.userList.map((item) => ({ ...item, isCheck: true, isCategory: false }));
      let userList = [...categoryList, ...userDataList];
      this.setState({ userList });
    }
  };

  removeClick = (row) => {
    let { selectUserList, selectUserIds } = this.state;
    selectUserList = selectUserList.filter((item) => item.id != row.id);
    selectUserIds = selectUserIds.filter((item) => item != row.id);
    this.setState({ selectUserList, selectUserIds });
  };

  changeRoleName = (e) => {
    let { queryData } = this.state;
    queryData.search = e.target.value;
    this.setState({ queryData }, () => {
      if (queryData.userType == null) {
        return message.error(formatMessage({ id: 'account.authManage.authorizationAddModal.selectTypeFirst', defaultMessage: '请选择类型，再搜索' }));
      } else {
        this.getList();
      }
    });
  };

  onClose = () => {
    this.setState({
      visible: false,
      queryData: {
        search: '',
        type: 0 /** 0 角色授权  1应用授权 2文档授权 */,
        categoryId: '',
        userType: null /** 0自建 1 应用 2通讯录 */,
        targetId: '',
      },
      userList:
        this.props.pageSource == 'application'
          ? [
              // { name: '通讯录', id: 'BM003', userType: 2, isCheck: false, isCategory: true },
            ]
          : [
              { name: formatMessage({ id: 'account.authManage.authorizationAddModal.selfBuiltUser' }), id: 'BM001', userType: 0, isCheck: false, isCategory: true },
              // { name: '系统用户', id: 'BM002', userType: 1, isCheck: false, isCategory: true },
              // { name: '通讯录', id: 'BM003', userType: 2, isCheck: false, isCategory: true },
            ],
      disabledSelectUserIds: [],
      selectUserIds: [],
      selectUserList: [
        // { name: '部门一', id: 'BM001' },
        // { name: '部门二', id: 'BM002' },
        // { name: '人员三', id: 'RY003' },
        // { name: '人员四', id: 'RY004' },
      ],
      activeUserList: [
        { name: formatMessage({ id: 'account.authManage.authorizationAddModal.contact' }), id: 'AB001' },
        // { name: '组织架构', id: 'BM002' },
        // { name: '研发部', id: 'RY003' },
      ],
    });
  };

  onSubmit = () => {
    const { selectUserList } = this.state;
    const { pageSource } = this.props;
    if (selectUserList && selectUserList.length > 0) {
      if (pageSource == 'application') {
        this.addAppBookUser();
      } else if (pageSource == 'document') {
        this.addDocUser();
      } else {
        this.addRole();
      }
    } else {
      return message.error(formatMessage({ id: 'account.authManage.authorizationAddModal.selectUser', defaultMessage: '请选择用户' }));
    }
  };

  addRole = async () => {
    const { queryData, selectUserList } = this.state;
    let authData = selectUserList.map((item) => ({
      type: item.isCategory ? 0 : 1,
      userType: item.userType,
      source: queryData.type,
      relId: item.id,
      targetId: queryData.targetId,
    }));
    let res = await postUserAuth({ authData });
    console.log(res);
    if (res.code === 0) {
      message.success(formatMessage({ id: 'account.authManage.authorizationAddModal.addSuccess' }));
      this.onClose();
      this.props.getList();
    }
  };

  onChange = (row) => {
    let { queryData, selectUserIds, selectUserList } = this.state;
    let list = [];
    if (selectUserIds.indexOf(row.id) > -1) {
      list = selectUserList.filter((item) => item.id != row.id);
      selectUserIds = selectUserIds.filter((item) => item != row.id);
    } else {
      list = [...selectUserList, { ...row, userType: queryData.userType }];
      selectUserIds = [...selectUserIds, row.id];
    }
    this.setState({ selectUserList: [...list], selectUserIds });
  };

  addAppBookUser = async () => {
    const { queryData, selectUserList } = this.state;
    let authData = selectUserList.map((item) => ({
      type: item.isCategory ? 0 : 1,
      userType: item.userType,
      source: 1,
      relId: item.id,
      targetId: queryData.targetId,
    }));
    let res = await postUserAuth({ authData });
    console.log(res);
    if (res.code === 0) {
      message.success(formatMessage({ id: 'account.authManage.authorizationAddModal.addSuccess' }));
      this.onClose();
      this.props.getList();
    }
  };

  addDocUser = async () => {
    const { queryData, selectUserList } = this.state;
    let authData = selectUserList.map((item) => ({
      type: item.isCategory ? 0 : 1,
      userType: item.userType,
      source: 2,
      relId: item.id,
      targetId: queryData.targetId,
      authType: this.props.queryAuthData.authType,
    }));
    let res = await postUserAuth({ authData });
    if (res.code === 0) {
      message.success(formatMessage({ id: 'account.authManage.authorizationAddModal.addSuccess' }));
      this.onClose();
      this.props.getList();
    } 
  };

  render() {
    const { visible, userList, disabledSelectUserIds, selectUserIds, selectUserList, queryData, activeUserList } = this.state;
    return (
      <Modal
        title={formatMessage({ id: 'account.authManage.authorizationAddModal.title'})}
        visible={visible}
        width={840}
        onCancel={this.onClose}
        footer={[
          <Button onClick={this.onClose} style={{ marginRight: 8 }}>
            {formatMessage({ id: 'account.authManage.authorizationAddModal.cancel', defaultMessage: '取消' })}
          </Button>,
          <Button onClick={this.onSubmit} type='primary'>
            {formatMessage({ id: 'account.authManage.authorizationAddModal.confirm', defaultMessage: '确定' })}
          </Button>,
        ]}
      >
        <div style={{ border: '1px solid #d0d3d6', borderRadius: '8px' }} className={styles.userAuthModal}>
          <div style={{ display: 'flex' }}>
            <div style={{ width: 'calc(50% - 1px)', padding: '16px', borderRight: '1px solid #d0d3d6' }}>
              <Input
                placeholder={formatMessage({ id: 'authorizationAddModal.searchPlaceholder', defaultMessage: '搜索用户、群组、部门或用户组' })}
                value={queryData.search}
                onChange={this.changeRoleName}
                onPressEnter={this.changeRoleName}
                maxLength={60}
              />
              <div
                style={{
                  lineHeight: '40px',
                  height: activeUserList && activeUserList.length > 0 ? '' : '16px',
                  display: queryData.search != '' && queryData.search.length > 0 ? 'none' : 'block',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                }}
              >
                <span>
                  {activeUserList.map((item, index) => {
                    return (
                      <span key={index}>
                        {activeUserList.length == index + 1 ? (
                          <span>{item.name}</span>
                        ) : (
                          <>
                            <span style={{ color: '#3E5BFF', cursor: 'pointer' }} onClick={() => this.setTitleClick(item)}>
                              {item.name}
                            </span>
                            <Icon type='right' style={{ margin: '0 5px' }} />
                          </>
                        )}
                      </span>
                    );
                  })}
                </span>
              </div>
              <Checkbox.Group
                style={{
                  width: 'calc(100% + 16px)',
                  maxHeight: '490px',
                  overflow: 'hidden auto',
                  marginLeft: -8,
                  marginTop: queryData.search != '' && queryData.search.length > 0 ? '16px' : '0px',
                }}
                value={selectUserIds}
              >
                <Row className={styles.userList}>
                  {userList.map((item, index) => {
                    return (
                      <>
                        {item && item.isCheck ? (
                          <Col span={24} className={styles.userLi} key={index}>
                            <Checkbox value={item.id} disabled={disabledSelectUserIds.indexOf(item.id) > -1} onChange={() => this.onChange(item)}>
                              {item.name}
                            </Checkbox>
                            {item.isCategory ? (
                              <span
                                style={
                                  selectUserIds.indexOf(item.id) > -1
                                    ? {
                                        cursor: 'no-drop',
                                        color: '#D4D4D4',
                                      }
                                    : {
                                        cursor: 'pointer',
                                      }
                                }
                              >
                                <span
                                  style={
                                    selectUserIds.indexOf(item.id) > -1
                                      ? {
                                          cursor: 'no-drop',
                                          pointerEvents: 'none',
                                          color: '#D4D4D4',
                                          backgroundColor: 'unset',
                                        }
                                      : {
                                          cursor: 'pointer',
                                        }
                                  }
                                  onClick={() => this.setClick(item)}
                                >
                                  <span>{formatMessage({ id: 'account.authManage.authorizationAddModal.subordinate' })}</span>
                                  <Icon type='right' />
                                </span>
                              </span>
                            ) : null}
                          </Col>
                        ) : (
                          <Col span={24} className={styles.userLi} key={index} style={{ cursor: 'pointer' }} onClick={() => this.setClick(item)}>
                            <label value={item.name} style={{ cursor: 'pointer' }}>
                              {item.name}
                            </label>
                            {item.isCategory ? (
                              <span>
                                <span>
                                  <span>{formatMessage({ id: 'account.authManage.authorizationAddModal.subordinate' })}</span>
                                  <Icon type='right' />
                                </span>
                              </span>
                            ) : null}
                          </Col>
                        )}
                      </>
                    );
                  })}
                </Row>
              </Checkbox.Group>
            </div>
            <div style={{ width: '50%', padding: '16px' }}>
              <div style={{ lineHeight: '36px' }}>
                {formatMessage({ id: 'account.authManage.authorizationAddModal.selectedCount', defaultMessage: '已选：' })} {selectUserList.length} 个
              </div>
              <ul
                style={{
                  padding: 0,
                  width: '100%',
                  maxHeight: '466px',
                  overflow: 'hidden auto',
                  marginLeft: -8,
                }}
                className={styles.selectUserList}
              >
                {selectUserList.map((item, index) => {
                  return (
                    <li className={styles.selectUserLi} key={index}>
                      <span>{item.name}</span>
                      <Icon type='close' onClick={() => this.removeClick(item)} />
                    </li>
                  );
                })}
              </ul>
            </div>
          </div>
        </div>
      </Modal>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(AuthorizationAddModal);
